package edu.xidian.onlinedocument.handler.interceptor;

import com.alibaba.fastjson.JSONObject;
import edu.xidian.onlinedocument.handler.AttributeName;
import edu.xidian.onlinedocument.handler.excpetions.custom.CustomException;
import edu.xidian.onlinedocument.service.DocumentService;
import edu.xidian.onlinedocument.service.UserService;
import edu.xidian.onlinedocument.utils.SpringUtil;
import edu.xidian.onlinedocument.views.Result;
import edu.xidian.onlinedocument.views.ResultCode;
import edu.xidian.onlinedocument.websocket.EditorSocketManager;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class EditorWebSocketInterceptor implements HandshakeInterceptor {

    private final Logger logger = LoggerFactory.getLogger(EditorWebSocketInterceptor.class);

    private final UserService userService;

    private final DocumentService documentService;

    // private int docId;

    public EditorWebSocketInterceptor() {
        // this.docId = docId;
        this.userService = SpringUtil.getBean("userService");
        this.documentService = SpringUtil.getBean("documentService");
    }

    /**
     * 处理客户端发出的握手请求的拦截器
     * 握手请求在WebSocket连接之前，在经过了以下的拦截才进入到WebSocketHandler，如果未通过拦截器则无法建立连接
     * @param request http请求
     * @param response http回应
     * @param wsHandler 自定义的WebSocketHandler，在WebSocketConfig中手动确定
     * @param attributes 即将封装在session里的属性，默认为空
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response,
                                   WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        if(request instanceof ServletServerHttpRequest) {
            logger.info("request hand shake: [{}] ", request.getURI());
            /*
                url: http://ip:port/websocket/documents/{docId}
                header: {
                    Sec-WebSocket-Protocol: [token]
                }
             */
            // 从uri中截取出docId
            Integer docId = Integer.parseInt(request.getURI().toString().split("/documents/")[1]);
            // token，注意是放在Sec-WebSocket-Protocol这个属性中的，websocket请求头只能自定义这个属性
            String token = ((ServletServerHttpRequest) request).getServletRequest().getHeader("Sec-WebSocket-Protocol");
            if (StringUtils.isBlank(token)) {
                // throw new CustomException(ResultCode.HTTP_HEADER_IS_NOT_EXIST_TOKEN);
                response.setStatusCode(HttpStatus.BAD_REQUEST);
                String json = JSONObject.toJSONString(new Result(ResultCode.TOKEN_CHECK_FAILED));
                ((ServletServerHttpResponse) response).getBody().write(json.getBytes(StandardCharsets.UTF_8));
                return false;
            }
            // 如果传递了token参数，后端响应的时候，也必须带上这个token响应，否则前端接收不到数据
            ((ServletServerHttpResponse) response).getServletResponse().setHeader("Sec-WebSocket-Protocol", token);
            // 根据token查询相应的userId
            Integer userId = userService.getUserIdByUserToken(token);
            if(userId == null) {
                // throw new CustomException(ResultCode.TOKEN_CHECK_FAILED);
                response.setStatusCode(HttpStatus.BAD_REQUEST);
                String json = JSONObject.toJSONString(new Result(ResultCode.USER_ID_NOT_EXIST));
                ((ServletServerHttpResponse) response).getBody().write(json.getBytes(StandardCharsets.UTF_8));
                return false;
            }

            // 检查用户是否有权限编辑文档
            if(!documentService.existsByDocIdAndEditorId(docId, userId)) {
                // throw new CustomException(ResultCode.DOCUMENT_IS_NOT_IN_EDITOR);
                response.setStatusCode(HttpStatus.BAD_REQUEST);
                String json = JSONObject.toJSONString(new Result(ResultCode.DOCUMENT_IS_NOT_IN_EDITOR));
                ((ServletServerHttpResponse) response).getBody().write(json.getBytes(StandardCharsets.UTF_8));
                return false;
            }
            String userNum = userService.getUserDataByUserId(userId).getUserNum();

            HttpSession session = ((ServletServerHttpRequest) request).getServletRequest().getSession(true);

            if(session == null) {
                return false;
            }
            // 加入相应的属性，从而传递给WebSocketHandle做处理
            // attributes实际上存储在session中，调用session.getAttributes()方法即可得到
            attributes.put(AttributeName.CLIENT_ID, userId);
            attributes.put(AttributeName.DOC_ID, docId);
            attributes.put(AttributeName.CLIENT_NUM, userNum);
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
                               ServerHttpResponse response,
                               WebSocketHandler wsHandler,
                               Exception exception) {

    }
}
